package com.lxy.phonebook.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxy.phonebook.constant.SystemConstant;
import com.lxy.phonebook.entity.CheckResult;
import com.lxy.phonebook.entity.PhoneBook;
import com.lxy.phonebook.service.PhoneService;
import com.lxy.phonebook.utils.JwtUtils;
import com.lxy.phonebook.utils.PinYinUtil;
import com.lxy.phonebook.utils.QiniuUploadUtils;
import com.lxy.phonebook.utils.R;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@RestController
@RequestMapping("/phonebook")
public class PhoneBookController {
    @Autowired
    PhoneService phoneService;

    @RequestMapping("/get")
    public List<PhoneBook> getAll() {
        return phoneService.list();
    }

    @RequestMapping("/load")
    public R load() {
        char[] letters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
                'W', 'X', 'Y', 'Z'};
        HashMap<String, List<PhoneBook>> map = new HashMap<>();
        for (char letter : letters) {
            //把char转换成string类型
            String initial = letter+"";
            //创建查询条件
            QueryWrapper<PhoneBook> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("initial",initial);
            //使用查询条件查询
            List<PhoneBook> list = phoneService.list(queryWrapper);
            map.put(initial,list);
        }
        //返回数据封装,便于前端看懂
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("data",map);
        return R.ok(resMap);
    }

    //刷新token的方法
    @RequestMapping("/fresh")
    public R fresh(HttpServletRequest request){
        //获取请求头中的token属性
        String token = request.getHeader("token");
        //解密，获取解密后的结果放入claims
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        System.out.println(claims);
        //创建新的token，claims中拿到结果重新创建token
        String newToken = JwtUtils.createJWT(claims.getId(), claims.getSubject(), SystemConstant.JWT_TTL);
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
        System.out.println(newToken);
        //返回新的token
        return R.ok(newToken);
    }

    //图片文件上传
    //MultipartFile: 专门用来进行文件上传的类
    @RequestMapping("/uploadImage")
    public R uploadImage(MultipartFile file){

        try {
            String originalFilename = file.getOriginalFilename();
            System.out.println(originalFilename);
            return QiniuUploadUtils.uploadImage(file);
        } catch (Exception e) {
            e.printStackTrace();
            return R.ok("出错了！");
        }
    }

    //添加数据的方法
    @RequestMapping("/add")
    public R add(@RequestBody PhoneBook phoneBook){
        try {
            System.out.println(phoneBook);
            phoneBook.setInitial(PinYinUtil.getPinYin(phoneBook.getName()).substring(0,1).toUpperCase());
            //添加操作
            boolean save = phoneService.save(phoneBook);
            System.out.println(save);
            if (save){
                return R.ok("添加成功");
            }else {
                return R.ok("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.ok("添加失败，出错了");
        }
    }

    //判断电话号码是否存在
    @RequestMapping("/a")
    public R a(@RequestBody PhoneBook phoneBook){
        QueryWrapper<PhoneBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber",phoneBook.getPhonenumber());
        PhoneBook one = phoneService.getOne(queryWrapper);
        if (one == null){
            return R.ok();
        }else {
            return R.error();
        }
    }

    //判断座机号码是否存在
    @RequestMapping("/b")
    public R b(@RequestBody PhoneBook phoneBook){
        QueryWrapper<PhoneBook> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telenumber",phoneBook.getTelenumber());
        PhoneBook one = phoneService.getOne(queryWrapper);
        if (one == null){
            return R.ok();
        }else {
            return R.error();
        }
    }

    //根据id获取数据
    @RequestMapping("/getData")
    public R b(Integer id){
        System.out.println(id);
        Map<String,Object> map = new HashMap<>();
        PhoneBook book = phoneService.getById(id);
        if (book != null){
            map.put("data",book);
            return R.ok(map);
        }else {
            return R.error("没有该数据");
        }
    }

    //修改数据
    @RequestMapping("/update")
    public R update(@RequestBody PhoneBook phoneBook){
        boolean b = phoneService.saveOrUpdate(phoneBook);
        if (b){
            return R.ok();
        }else {
            return R.error();
        }
    }

    @RequestMapping("/delPhone/{id}")
    public R delPhone(@PathVariable(value = "id") Integer id){
        boolean b = phoneService.removeById(id);
        if (b){
            return R.ok();
        }else {
            return R.error();
        }
    }
}
